#ifndef SERIALWORKER_H
#define SERIALWORKER_H

#include <QSerialPort>
#include "QVector"
#include <qfile.h>
#include <qmutex.h>
#include <qtextstream.h>
#include <qtimer.h>
#include "../dll/MultiUSBDongleLib.h"

class SerialWorker : public QObject {
    Q_OBJECT
public:
    explicit SerialWorker(QObject *parent = nullptr);
    ~SerialWorker();

    void MultiUSBDongleAPI_Init();
    void ECGStartOrder();
    void ECGStopOrder();

    void EEGStopOrder();
    void EEGStartOrder();

    void StartCompute();
    void getDeviceState();



signals:
    void newECGWaveData(QVector<double> ecgdata,QVector<double> respdata);
    void newEEGWaveData(QVector<double> leftEEGdata,QVector<double> rightEEGdata,QVector<double> irPPGdata,QVector<double> redPPGdata);

    void OpenSeriaPortSuccess();
    void CloseSerialPortSucess();
    void errorOccurred(const QString &error);
    void newEEGRealIndexData(QVector<double>realTimeIndex);
    void newEEGEnergyIndexData(QVector<double>engeryIndex,QVector<double>f,QVector<double>psd);

public:
    void ColseSerialPort();
    void OpenSerialPort(const QString &portName, qint32 baudRate);

private slots:
    void readyRead();
    void updateRealTimeIndex();
    void updateBrainEneryIndex();
private:
    QSerialPort *m_serial = nullptr;
    QByteArray m_buffer;
    bool m_running = true;
    bool StartCollectFlag,isSaveRawData;

    unsigned char dualeegStartCollectOrder[13],dualeegStopCollectOrder[13];
    unsigned char ecgHolterStartCollectOrder[27],ecgHolterStopCollectOrder[27],ecgHolterInfoOrder[27];
    QTimer timer,timerRealTimeIndex,timerFFT3DAnaShow,timerForStep,timer_DeviceState;
    int stopNum;
    int SampleNum;
    int stepNum;
    int stepIndex;
    // std::ofstream outFile,outFile_UserInfo,outFile_Design;
    QTextStream stream,stream_info;
    QFile file;
    void WriteOrder(unsigned char *order);
    QString fileName,fileName_userInfo,fileName_design;
    QMutex m_mutex;



    void initTimers();

};

#endif // SERIALWORKER_H
